package io.shuttle.mbe_app.ui.page

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.webkit.ConsoleMessage
import android.webkit.JsPromptResult
import android.webkit.JsResult
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import android.widget.Toast
import androidx.activity.compose.LocalActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.pulltorefresh.PullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import io.shuttle.mbe_app.permission.rememberMultiplePermissionsState
import io.shuttle.mbe.core.Ability
import io.shuttle.mbe.core.ReplyBody
import io.shuttle.mbe.core.Wab
import kotlinx.coroutines.delay
import java.lang.ref.WeakReference

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MBECoreTestPage(link: String, pullToRefreshState: PullToRefreshState) {
    val context = LocalContext.current
    val activity = LocalActivity.current

    val launcher = rememberMultiplePermissionsState(
        permissions = listOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
        )
    )
    if (launcher.allPermissionsGranted) {
        Toast.makeText(context, "已授权", Toast.LENGTH_SHORT).show()
    }
    SideEffect {
        if (!launcher.allPermissionsGranted) {
            launcher.launchMultiplePermissionRequest()
        }
    }
    WebView.setWebContentsDebuggingEnabled(true)
    var webView: WebView? by remember { mutableStateOf(null) }
    var wab: Wab? by remember { mutableStateOf(null) }
    var customView: View? by remember { mutableStateOf(null) }
    var suv by remember { mutableStateOf(0) }
    var customViewCallback : WebChromeClient.CustomViewCallback? by remember { mutableStateOf(null) }
    if (pullToRefreshState.isAnimating) {
        LaunchedEffect(true) {
            webView?.reload()
            delay(1000)
            pullToRefreshState.animateToHidden()
        }
    }
    Column(
        modifier = Modifier.background(Color.Black)
    ) {
        //        TextButton(
//            border = BorderStroke(1.dp, Color.Green),
//            elevation = ButtonDefaults.elevatedButtonElevation(),
//            onClick = {
//                wab?.postMessage(
//                    mutableMapOf("1" to 2).toJSObject()?.toString() ?: "",
//                    legacyReply = {
//                        Logger.d("[Wab.postMessage] $it")
//                    })
//            }) {
//            Text("send message to webview!")
//        }
        Box(
            modifier = Modifier
                .background(Color.White)
                .padding(10.dp)
                .fillMaxSize()
        ) {
            AndroidView(
                modifier = Modifier
                    .fillMaxSize(),
                factory = { context ->
                    WebView.setWebContentsDebuggingEnabled(true)
                    WebView(context).also {
                        it.layoutParams = ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT
                        )
                        it.settings.apply {
                            @SuppressLint("SetJavaScriptEnabled")
                            javaScriptEnabled = true
                            allowFileAccess = true
                            domStorageEnabled = true
                            setSupportZoom(false)
                            builtInZoomControls = false
                            displayZoomControls = false
                            mediaPlaybackRequiresUserGesture = false
                        }
                        it.isHorizontalScrollBarEnabled = false
                        it.isHorizontalFadingEdgeEnabled = false
                        it.overScrollMode = WebView.OVER_SCROLL_NEVER

                        it.webViewClient = object : WebViewClient() {
                            override fun onPageStarted(
                                view: WebView?,
                                url: String?,
                                favicon: Bitmap?
                            ) {
                                super.onPageStarted(view, url, favicon)
                            }

                            override fun onPageFinished(view: WebView?, url: String?) {
                                super.onPageFinished(view, url)
                            }
                        }

                        it.webChromeClient = object : WebChromeClient() {
                            override fun onPermissionRequest(request: PermissionRequest?) {
                                request?.grant(request.resources)
                            }

                            override fun onJsAlert(
                                view: WebView?,
                                url: String?,
                                message: String?,
                                result: JsResult?
                            ): Boolean {
                                result?.confirm()
                                return super.onJsAlert(view, url, message, result)
                            }

                            override fun onJsConfirm(
                                view: WebView?,
                                url: String?,
                                message: String?,
                                result: JsResult?
                            ): Boolean {
                                result?.confirm()
                                return super.onJsConfirm(view, url, message, result)
                            }

                            override fun onJsPrompt(
                                view: WebView?,
                                url: String?,
                                message: String?,
                                defaultValue: String?,
                                result: JsPromptResult?
                            ): Boolean {
                                result?.confirm()
                                return super.onJsPrompt(view, url, message, defaultValue, result)
                            }

                            override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
                                Log.e("【6️⃣】", consoleMessage?.message().toString())
                                return super.onConsoleMessage(consoleMessage)
                            }

                            override fun getDefaultVideoPoster(): Bitmap? {

                                return super.getDefaultVideoPoster()
                            }

                            override fun onShowCustomView(
                                view: View?,
                                callback: CustomViewCallback?
                            ) {
                                if (customView != null) {
                                    onHideCustomView()
                                    return
                                }
                                customView = view
                                customViewCallback = callback

                                activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

                                (activity?.window?.decorView as FrameLayout).addView(
                                    customView,
                                    FrameLayout.LayoutParams(-1, -1)
                                )
                                customView?.systemUiVisibility =
                                    View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                                super.onShowCustomView(view, callback)
                            }

                            override fun onHideCustomView() {
                                if (customViewCallback == null) return
                                activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                                (activity?.window?.decorView as FrameLayout).removeView(customView)
                                customViewCallback?.onCustomViewHidden()
                                customViewCallback = null
                                activity?.window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
                                super.onHideCustomView()
                            }
                        }
                    }
                }, update = {
                    webView = it
                    val completed = Ability.Value(data = "completed")
                    wab = Wab(
                        WeakReference(it),
                        preferWebChannel = true,
                        preferWebListener = true
                    ).apply {
                        addAbility(
                            "toast",
                            Ability.Function { message, postMessageBody, sourceOrigin, isMainFrame, reply ->
                                Toast.makeText(context, message.data, Toast.LENGTH_SHORT).show()
                                reply?.replyJs(
                                    ReplyBody(
                                        data = "ok",
                                    ), this@apply.wabSupportType
                                )
                            })
                        addAbility(
                            "heavy",
                            Ability.Function { message, postMessageBody, sourceOrigin, isMainFrame, reply ->
                                webView!!.postDelayed({
                                    reply?.replyJs(
                                        ReplyBody(data = "ok"),
                                        this@apply.wabSupportType
                                    )
                                }, 1000)
                            }
                        )
                        addAbility("completed", completed)
                        addAbility(
                            "PlatformVersion",
                            Ability.Function { message, postMessageBody, sourceOrigin, isMainFrame, reply ->
                                reply?.replyJs(
                                    ReplyBody(data = "0.1.0.1"),
                                    this@apply.wabSupportType
                                )
                            })
                    }
                    it.postDelayed({
                        completed.data = "unfinished"
                    }, 5000)
                    it.loadUrl(link)
                })

        }
    }
}